<template>
  <a-upload
      :action="`${baseUrl}/file/upload`"
      :headers="{'Authorization': `Bearer ${token}`}"
      v-model:file-list="fileList"
      :limit="limit"
      :disabled="disabled"
      :name="formDataName"
      :accept="accept"
      :onSuccess="uploadSuccess"
      :onBeforeRemove="beforeRemove"
  />
</template>

<script setup lang="ts">
import {getToken} from "@/utils/auth";
import {ref, watch} from "vue";
import {FileItem} from "@arco-design/web-vue";

const emit = defineEmits(["update:modelValue"]);
const props = defineProps({
  modelValue: {
    type: Array,
    default: [],
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  limit: {
    type: Number,
    default: 1
  },
  accept: {
    type: String,
    default: ''
  },
  formDataName: {
    type: String,
    default: 'file'
  }
})

const token = getToken();
const baseUrl = import.meta.env.VITE_API_BASE_URL;

const fileList = ref<any>([]);
const limit = ref<number>(props.limit);
const disabled = ref<boolean>(props.disabled);
const accept = ref<string>(props.accept);
const formDataName = ref<string>(props.formDataName);
const resultList = ref<any[]>(props.modelValue);

// 上传成功时
const uploadSuccess = (res?: any) => {
  const {code, data} = res.response;
  if (code === 200 && data) {
    resultList.value.push(data);
    let obj = {
      url: baseUrl + data,
      name: data.substring(data.lastIndexOf('/') + 1),
    }
    fileList.value.push(obj);
  }
};
// 移除
const beforeRemove = (fileItem: FileItem) => {
  console.log(fileItem)
  console.log(resultList)
  // @ts-ignore
  resultList.value.map((item, index) => {
    // @ts-ignore
    if (fileItem.url?.includes(item)) {
      resultList.value.splice(index, 1);
      fileList.value.splice(index, 1);
    }
  });
  return Promise.resolve(true);
}

watch(
    () => resultList.value,
    (newVal) => {
      emit("update:modelValue", newVal);
    },
    {deep: true}
);

watch(
    () => props.modelValue,
    (newVal) => {
      fileList.value = newVal.map((item: any) => {
        return {
          url: baseUrl + item,
          name: item.substring(item.lastIndexOf('/') + 1),
        }
      });
      resultList.value = newVal;
    },
    {deep: true}
);

</script>

<style scoped lang="less">

</style>
